﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace PhotoMgr.src.common
{
    public partial class PageBar : UserControl
    {
        private bool autoLoadPageData = false;
        public delegate void PageChangedEvent(int page);
        public event PageChangedEvent PageChanged;

        public PageBar()
        {
            InitializeComponent();
        }
                
        private PageData pageSource;

        public PageData PageSource
        {
            get { return pageSource; }
            set { 
                pageSource = value;

                if (pageSource == null) return;

                autoLoadPageData = false;                
                nud_page.Value = pageSource.CurrentPage;
                nud_page.Maximum = pageSource.TotalPages;
                label4.Text = string.Format( "/{0}({1})", pageSource.TotalPages, pageSource.TotalRecords);
                btn_first.Enabled = btn_previous.Enabled = (nud_page.Value != 1);
                btn_last.Enabled = btn_next.Enabled = (nud_page.Value != pageSource.TotalPages);
                autoLoadPageData = true;
            }
        }

        private void btn_first_Click(object sender, EventArgs e)
        {
            nud_page.Value = 1;
        }

        private void btn_previous_Click(object sender, EventArgs e)
        {
            if( nud_page.Value > 1 )
                nud_page.Value -= 1;
        }

        private void btn_next_Click(object sender, EventArgs e)
        {
            if (nud_page.Value < pageSource.TotalPages)
                nud_page.Value += 1;
        }

        private void btn_last_Click(object sender, EventArgs e)
        {
            nud_page.Value = pageSource.TotalPages;
        }

        private void btn_refresh_Click(object sender, EventArgs e)
        {
            nud_page_ValueChanged(nud_page, new EventArgs());
        }

        private void nud_page_ValueChanged(object sender, EventArgs e)
        {
            if (!autoLoadPageData) 
                return;

            if (PageChanged != null) 
                PageChanged((int)nud_page.Value);

            btn_first.Enabled = btn_previous.Enabled = (nud_page.Value != 1);
            btn_last.Enabled = btn_next.Enabled = (nud_page.Value != pageSource.TotalPages);
            
        }

        public void RefreshData() {
            nud_page_ValueChanged(nud_page, new EventArgs());
        }
    }
}
